<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" @click="handleAdd">添加物流公司</el-button>
        </div>
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">公司名称：</span>
                <el-input placeholder="输入公司名称" v-model.trim="search_text" size="default" clearable></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">计费方式：</span>
                <el-select v-model="valuation_type" clearable placeholder="请选择计费方式">
                    <el-option label="全部" value="0" />
                    <el-option label="按件数" value="1" />
                    <el-option label="按重量" value="2" />
                    <el-option label="按体积" value="3" />
                    <el-option label="按装箱" value="4" />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">包装配置：</span>
                <el-select v-model="pack_config" clearable placeholder="请选择包装配置">
                    <el-option label="全部" value="0" />
                    <el-option label="未配置" value="1" />
                    <el-option label="已配置" value="2" />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
            </div>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column prop="company_id" label="ID" width="80" fixed="left"></el-table-column>
            <el-table-column prop="title" label="公司名称" width="200" fixed="left"></el-table-column>
            <el-table-column prop="phone" label="联系电话" width="130"></el-table-column>
            <el-table-column label="计费方式" width="90">
                <template #default="{ row }">
                    <span style="color: #4b93fa">{{ row.valuation_type_label }}</span>
                </template>
            </el-table-column>
            <el-table-column label="包装配置" width="80">
                <template #default="{ row }">
                    <span style="color: #4b93fa">{{ row.pack_config == 0 ? "未配置" : "已配置" }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="min_weight" label="最小配送重量(kg)" width="140"> </el-table-column>
            <el-table-column prop="max_weight" label="最大配送重量(kg)" width="140"> </el-table-column>
            <el-table-column label="排序" width="130">
                <template #default="{ row }">
                    <el-input
                        v-model.trim="row.order_by"
                        clearable
                        placeholder="请输入排序数字"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        style="width: 100px"
                        @change="() => inputSort(row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="intro" label="配送备注" min-width="200">
                <template #default="{ row }">
                    <el-popover placement="top" :width="800" trigger="hover" :content="row.intro">
                        <template #reference>
                            <div class="line-two">{{ row.intro }}</div>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="created_at_label" label="添加时间" width="160"> </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button class="theme-btn" link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button class="theme-btn" link type="primary" @click="handlePack(row)">包装配置</el-button>
                    <el-popconfirm title="确定删除吗？" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(row)">
                        <template #reference>
                            <el-button class="theme-btn" link type="primary" style="margin-left: 14px">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 添加/编辑 -->
        <el-drawer
            :title="company_type == 1 ? '添加物流公司' : '编辑物流公司'"
            v-model="dialogCompany"
            direction="rtl"
            size="840px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeCompany"
        >
            <el-form ref="ruleCompanyRef" :model="ruleCompanyForm" :rules="ruleCheckCompany" label-width="140px">
                <el-form-item label="物流公司分组" prop="group_id">
                    <el-select v-model="ruleCompanyForm.group_id" clearable placeholder="请选择物流公司分组">
                        <el-option :label="item.group_name" :value="item.group_id" v-for="item in groups" :key="item.group_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="公司名称" prop="title">
                    <el-input v-model.trim="ruleCompanyForm.title" clearable placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="联系电话" prop="tel">
                    <el-input v-model.trim="ruleCompanyForm.tel" oninput="value=value.replace(/[^\d-]/g,'')" clearable placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="计费方式" prop="valuation_type">
                    <el-radio-group v-model="ruleCompanyForm.valuation_type" :disabled="company_type == 2">
                        <el-radio label="0">按件数</el-radio>
                        <el-radio label="1">按重量</el-radio>
                        <el-radio label="2">按体积</el-radio>
                        <el-radio label="3">按装箱</el-radio>
                    </el-radio-group>
                    <p class="input-tips">编辑时不支持修改计费方式，请添加的时候确认好计费方式</p>
                </el-form-item>
                <el-form-item label="最小配送重量(kg)" prop="min_weight">
                    <el-input
                        v-model.trim="ruleCompanyForm.min_weight"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入最小配送重量(kg)"
                    />
                </el-form-item>
                <el-form-item label="最大配送重量(kg)" prop="max_weight">
                    <el-input
                        v-model.trim="ruleCompanyForm.max_weight"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入最大配送重量(kg)"
                    />
                </el-form-item>
                <el-form-item label="排序" prop="order_by" required>
                    <el-input v-model.trim="ruleCompanyForm.order_by" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入排序数字" />
                </el-form-item>
                <el-form-item label="配送备注" prop="remark">
                    <el-input v-model.trim="ruleCompanyForm.remark" :rows="6" type="textarea" clearable placeholder="请输入配送备注" />
                </el-form-item>
                <el-form-item label="详细介绍">
                    <div class="editor-box">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
                        <Editor
                            style="height: 440px; overflow-y: hidden"
                            v-model="valueHtml"
                            :defaultConfig="editorConfig"
                            mode="default"
                            @onCreated="handleCreated"
                        />
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="drawer-footer flexs-center">
                    <el-button type="primary" :loading="form_loading" @click="submitCompanyForm(ruleCompanyRef)">
                        {{ company_type == 1 ? "确认添加" : "确认修改" }}
                    </el-button>
                    <el-button @click="resetCompanyForm(ruleCompanyRef)">重置</el-button>
                </div>
            </template>
        </el-drawer>

        <!-- 选择包装配置 -->
        <el-drawer
            title="选择包装配置"
            v-model="dialogPack"
            direction="rtl"
            size="700px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="dialogPack = false"
        >
            <el-table
                ref="multipleTableRef"
                class="table-mb"
                :data="packs"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
                v-loading="table_loading"
                @selection-change="handleAllSelected"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="title" label="包装名称"> </el-table-column>
                <el-table-column label="包装规格">
                    <template #default="{ row }">
                        {{ box_level_arrs[row.box_level] }}
                    </template>
                </el-table-column>
                <el-table-column prop="weight" label="可装重量"></el-table-column>
                <el-table-column prop="amount" label="打包费"></el-table-column>
            </el-table>
            <template #footer>
                <div class="drawer-footer flexs-center">
                    <el-button type="primary" :loading="form_loading" @click.stop="clickSelectPack">确认选择</el-button>
                </div>
            </template>
        </el-drawer>

        <go-back></go-back>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, shallowRef, onBeforeUnmount, nextTick } from "vue"
import { Search } from "@element-plus/icons-vue"
import OneLoad from "@mixins/one-load"
import GoBack from "@components/GoBack.vue"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    ruleCompanyRef.value = null

    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, search_text, search_btn, pubParams, pubRefreshParams, getdata } = OneLoad()


// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        so: search_text.value,
        valuation_type: valuation_type.value,
        pack_config: pack_config.value,
    }
    getdata("express/company/index", params)
}

// 搜索
const valuation_type = ref("") // 计费方式[0:全部,1:按件数,2:按重量,3:按体积,4:按装箱]
const pack_config = ref("") // 包装配置[0:全部,1:未配置,2:已配置]
const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

/**
 * 添加/编辑
 * @property {Boolean} dialogCompany 添加/编辑弹窗状态
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Number} company_type 弹窗类型，1是添加，2是编辑
 * @property {Array} ruleCompanyRef 表单规则
 * @property {Object} ruleCompanyForm  表单字段
 * @property {Object} ruleCheckCompany  表单提示
 * @property {Function} submitCompanyForm 提交表单
 * @property {Function} closeCompany 关闭弹窗
 */
const dialogCompany = ref(false)
const form_loading = ref(false)
const company_type = ref(1)
const ruleCompanyRef = ref(null)
const ruleCompanyForm = reactive({
    id: "",
    group_id: "",
    title: "",
    tel: "",
    min_weight: "",
    max_weight: "",
    remark: "",
    order_by: "100",
    valuation_type: "",
})
const ruleCheckCompany = reactive({
    title: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
    // tel: [{ required: true, validator: proxy.$util.validPhone, trigger: "blur" }],
    tel: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
    valuation_type: [{ required: true, message: "请选择计费方式", trigger: "change" }],
    group_id: [{ required: true, message: "请选择物流公司分组", trigger: "change" }],
    min_weight: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    max_weight: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    order_by: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
})
const submitCompanyForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            // const texts = editorRef.value.getText()
            let htmls = ""
            if (valueHtml.value) {
                htmls = valueHtml.value.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
            }
            let data = {
                title: ruleCompanyForm.title,
                group_id: ruleCompanyForm.group_id,
                phone: ruleCompanyForm.tel,
                valuation_type: ruleCompanyForm.valuation_type,
                min_weight: ruleCompanyForm.min_weight,
                max_weight: ruleCompanyForm.max_weight,
                intro: ruleCompanyForm.remark,
                order_by: ruleCompanyForm.order_by,
                content: htmls,
            }
            if (company_type.value == 2) {
                data.company_id = ruleCompanyForm.id
            }
            let url = company_type.value == 1 ? "express/company/add" : "express/company/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogCompany.value = false
                        proxy.$message({ message: `${company_type.value == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetCompanyForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    editorRef.value.setHtml("<p></p>") // 重置富文本
}
const closeCompany = () => {
    dialogCompany.value = false
    resetCompanyForm(ruleCompanyRef.value)
}
// 添加
const handleAdd = () => {
    company_type.value = 1
    dialogCompany.value = true
    getGroups()
}
// 编辑
const handleEdit = (row) => {
    dialogCompany.value = true
    company_type.value = 2
    getGroups()
    getEditDetail(row.company_id)
}
// 获取编辑详情
function getEditDetail(id) {
    proxy.$axios
        .get("express/company/update", {
            params: {
                company_id: id,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                ruleCompanyForm.id = result.company_id
                ruleCompanyForm.group_id = result.group_id
                ruleCompanyForm.title = result.title
                ruleCompanyForm.tel = result.phone
                ruleCompanyForm.min_weight = result.min_weight
                ruleCompanyForm.max_weight = result.max_weight
                ruleCompanyForm.remark = result.intro
                ruleCompanyForm.order_by = result.order_by
                ruleCompanyForm.valuation_type = String(result.valuation_type)

                valueHtml.value = result.content.replace(/<img [^>]*src=['"]/g, `<img src="${proxy.imgUrl}`) // 往图片追加根域名和'/'
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 物流分组
const groups = ref([])
function getGroups() {
    proxy.$axios
        .get("express/company/search")
        .then((res) => {
            if (res.data.code == 0) {
                groups.value = res.data.data.group_list
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 包装配置
const itemObjs = ref([])
const packs = ref([])
const dialogPack = ref(false)
const table_loading = ref(false)
const box_level_arrs = ["mini1", "mini2", "mini3", "mini4", "特小", "小包", "中包", "大包"]
const handlePack = (row) => {
    dialogPack.value = true
    itemObjs.value = row
    getPack()
}
const multipleTableRef = ref(null)
function getPack() {
    table_loading.value = true
    proxy.$axios
        .get("express/company/packConfig", {
            params: {
                company_id: itemObjs.value.company_id,
            },
        })
        .then((res) => {
            table_loading.value = false
            if (res.data.code == 0) {
                let result = res.data.data
                nextTick(() => {
                    result.map((item) => {
                        if (item.selected == 1) {
                            multipleTableRef.value.toggleRowSelection(item, true)
                        }
                    })
                })

                packs.value = result
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            table_loading.value = false
        })
}
/**
 * 批量选择包装配置操作
 * @param {Array} ids 选中数组的集合
 */
const ids = ref([])
const handleAllSelected = (val) => {
    let arrs = []
    for (let i = 0; i < val.length; i++) {
        arrs.push(val[i].pack_id)
    }
    ids.value = arrs
}
// 确认选择
const clickSelectPack = () => {
    if (ids.value.length == 0) {
        proxy.$message({ message: "请至少选择一个包装配置", type: "warning" })
        return
    }
    form_loading.value = true
    proxy.$axios
        .post("express/company/packConfig", {
            company_id: itemObjs.value.company_id,
            pack: ids.value,
        })
        .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
                dialogPack.value = false
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            form_loading.value = false
        })
}

// 删除
const handleDelete = (row) => {
    proxy.$axios
        .post("express/company/delete", {
            company_id: row.company_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 排序
const inputSort = (row) => {
    if (!row.order_by) {
        proxy.$message({ message: "请输入排序数字", type: "warning" })
        return
    }
    proxy.$axios
        .post("express/company/sort", {
            company_id: row.company_id,
            order_by: row.order_by,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {String} valueHtml 输入内容
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const valueHtml = ref("") // 内容 HTML
// 排除不需要的菜单
const toolbarConfig = {
    excludeKeys: ["insertLink", "insertImage", "editImage", "viewImageLink", "group-video", "emotion", "fullScreen"],
}
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
// 自定义上传
editorConfig.MENU_CONF["uploadImage"] = {
    async customUpload(file, insertFn) {
        let data = new FormData()
        data.append("from", "article")
        data.append("image", file)
        proxy.$axios
            .post("upload/image", data)
            .then((res) => {
                if (res.data.code == 0) {
                    let url = proxy.imgUrl + res.data.data.path
                    insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
                } else {
                    proxy.$message({ message: res.data.msg, type: "error" })
                }
            })
            .catch((err) => {})
    },
}
</script>
<script>
export default {
    name: "LogisticsCompany",
}
</script>

<style lang="less" scoped>
.editor-box {
    border: 1px solid #ccc;
    border-radius: 2px;
}
</style>

<style>
.el-popper {
    max-width: 500px;
}
</style>
